package com.shuda.business.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuda.business.channel.entity.ChannelEntity;
import com.shuda.business.channel.mapper.ChannelMapper;
import com.shuda.business.channel.service.ChannelService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.security.SecurityUtils;
import com.shuda.common.utils.PageResult;
import com.shuda.common.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 渠道服务实现类
 */
@Service
@RequiredArgsConstructor
public class ChannelServiceImpl implements ChannelService {

    private final ChannelMapper channelMapper;
    private static final Logger log = LoggerFactory.getLogger(ChannelServiceImpl.class);

    @Override
    public PageResult<ChannelEntity> getChannelPage(PageDTO pageDTO, QueryWrapper<ChannelEntity> queryWrapper) {
        Page<ChannelEntity> page = PageUtils.buildPage(pageDTO);
        Page<ChannelEntity> channelPage = channelMapper.selectPage(page, queryWrapper);
        // 明确返回com.shuda.common.utils.PageResult，避免同名类造成的类型不兼容
        return new com.shuda.common.utils.PageResult<>(
                channelPage.getRecords(),
                channelPage.getTotal(),
                channelPage.getCurrent(),
                channelPage.getSize()
        );
    }

    @Override
    public ChannelEntity getById(Long id) {
        return channelMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createChannel(ChannelEntity channel) {
        // 检查渠道编码是否已存在
        QueryWrapper<ChannelEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("channel_code", channel.getChannelCode());
        if (channelMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("渠道编码已存在");
        }
        
        // 设置默认状态（Integer：1启用，0禁用）
        if (channel.getStatus() == null) {
            channel.setStatus(1);
        }
        
        // 设置创建/更新审计信息（对齐 BaseEntity：createdAt/createdBy/updatedAt/updatedBy）
        channel.setCreatedAt(LocalDateTime.now());
        channel.setCreatedBy(SecurityUtils.getCurrentUserId());
        channel.setUpdatedAt(LocalDateTime.now());
        channel.setUpdatedBy(SecurityUtils.getCurrentUserId());
        channel.setDeleted(0);
        
        channelMapper.insert(channel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChannel(ChannelEntity channel) {
        // 检查渠道是否存在
        ChannelEntity existingChannel = channelMapper.selectById(channel.getId());
        if (existingChannel == null) {
            throw new BusinessException("渠道不存在");
        }
        
        // 如果更新渠道编码，需要检查是否已存在
        if (channel.getChannelCode() != null && !channel.getChannelCode().equals(existingChannel.getChannelCode())) {
            QueryWrapper<ChannelEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("channel_code", channel.getChannelCode());
            if (channelMapper.selectCount(queryWrapper) > 0) {
                throw new BusinessException("渠道编码已存在");
            }
        }
        
        // 设置更新审计信息
        channel.setUpdatedAt(LocalDateTime.now());
        channel.setUpdatedBy(SecurityUtils.getCurrentUserId());
        
        channelMapper.updateById(channel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChannel(Long id) {
        ChannelEntity channel = channelMapper.selectById(id);
        if (channel == null) {
            throw new BusinessException("渠道不存在");
        }
        
        // 逻辑删除
        channel.setDeleted(1);
        channel.setUpdatedAt(LocalDateTime.now());
        channel.setUpdatedBy(SecurityUtils.getCurrentUserId());
        channelMapper.updateById(channel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChannels(List<Long> ids) {
        for (Long id : ids) {
            deleteChannel(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChannelStatus(Long id, String status) {
        ChannelEntity channel = channelMapper.selectById(id);
        if (channel == null) {
            throw new BusinessException("渠道不存在");
        }
        
        // 将字符串状态映射为整型："active"/"enabled"/"1" -> 1，其它 -> 0
        Integer mappedStatus = ("active".equalsIgnoreCase(status)
                || "enabled".equalsIgnoreCase(status)
                || "1".equals(status)) ? 1 : 0;
        channel.setStatus(mappedStatus);
        channel.setUpdatedAt(LocalDateTime.now());
        channel.setUpdatedBy(SecurityUtils.getCurrentUserId());
        channelMapper.updateById(channel);
    }

    @Override
    public boolean testChannel(Long id) {
        ChannelEntity channel = channelMapper.selectById(id);
        if (channel == null) {
            throw new BusinessException("渠道不存在");
        }
        
        try {
            // 根据渠道类型进行不同的连接测试
            switch (channel.getChannelType()) {
                case "api":
                    return testApiChannel(channel);
                case "h5":
                    return testH5Channel(channel);
                case "miniapp":
                    return testMiniappChannel(channel);
                default:
                    log.warn("未知的渠道类型: {}", channel.getChannelType());
                    return false;
            }
        } catch (Exception e) {
            log.error("渠道连接测试失败: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public ChannelEntity getChannelConfig(Long id) {
        return channelMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChannelConfig(Long id, ChannelEntity config) {
        ChannelEntity channel = channelMapper.selectById(id);
        if (channel == null) {
            throw new BusinessException("渠道不存在");
        }
        
        // 只更新配置相关字段（对齐 ChannelEntity 字段）
        channel.setBaseUrl(config.getBaseUrl());
        channel.setApiKey(config.getApiKey());
        channel.setApiSecret(config.getApiSecret());
        channel.setCallbackUrl(config.getCallbackUrl());
        channel.setHeaders(config.getHeaders());
        channel.setParamMapping(config.getParamMapping());
        channel.setTimeout(config.getTimeout());
        channel.setRetryCount(config.getRetryCount());
        channel.setRetryInterval(config.getRetryInterval());
        channel.setMaxConcurrency(config.getMaxConcurrency());
        channel.setUpdatedAt(LocalDateTime.now());
        channel.setUpdatedBy(SecurityUtils.getCurrentUserId());
        
        channelMapper.updateById(channel);
    }

    /**
     * 测试API渠道连接
     */
    private boolean testApiChannel(ChannelEntity channel) {
        // TODO: 实现API渠道连接测试逻辑
        log.info("测试API渠道连接: {}", channel.getChannelName());
        return true;
    }

    /**
     * 测试H5渠道连接
     */
    private boolean testH5Channel(ChannelEntity channel) {
        // TODO: 实现H5渠道连接测试逻辑
        log.info("测试H5渠道连接: {}", channel.getChannelName());
        return true;
    }

    /**
     * 测试小程序渠道连接
     */
    private boolean testMiniappChannel(ChannelEntity channel) {
        // TODO: 实现小程序渠道连接测试逻辑
        log.info("测试小程序渠道连接: {}", channel.getChannelName());
        return true;
    }
}